package com.sqlist.share;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sqlist.share.dto.LoginResultDTO;
import com.sqlist.share.dto.MessageDTO;
import com.sqlist.share.util.Callback;
import com.sqlist.share.util.Const;
import com.sqlist.share.util.GsonUtils;
import com.sqlist.share.util.HttpUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by SqList on 2018/6/12.
 */

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "Share - LoginActivity";

    private void setStatusBar() {
        // 禁止横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 去掉Android原生的标题栏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);

        // 将状态栏设成透明
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = this.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }

        // android6.0以后可以对状态栏文字颜色和图标进行修改
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    private EditText usernameEditText;
    private EditText passwordEditText;
    private ImageView loginBtnImageView;
    private TextView toRegisterBtn;

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    private static Handler handler;

    public static Handler getHandler() {
        return handler;
    }

    private void requestPower() {
        //判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_WIFI_STATE)
                    || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {//这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限
                Toast.makeText(LoginActivity.this, "没有权限可能导致某些服务不能正常执行，请手动开启", Toast.LENGTH_LONG).show();
            } else {
                //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStatusBar();
        setContentView(R.layout.activity_login);
        Log.i(TAG, "onCreate()");

        requestPower();

        init();
    }

    public void init() {
        usernameEditText = findViewById(R.id.usernameEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginBtnImageView = findViewById(R.id.loginBtnImageView);
        toRegisterBtn = findViewById(R.id.toRegisterBtn);

        preferences = getSharedPreferences("usernameAndToken", MODE_PRIVATE);
        editor = preferences.edit();

        loginBtnImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();

                final Map<String, String> loginMap = new HashMap<>();
                loginMap.put("username", username);
                loginMap.put("password", password);

                HttpUtils.getInstance().post("http://" + Const.HOST + ":" + Const.HTTP_PORT + "/login", loginMap, new Callback() {
                    @Override
                    public void onSuccess(Object o) {
                        MessageDTO<LoginResultDTO> loginResultDTOMessageDTO = (MessageDTO<LoginResultDTO>) o;
                        Log.d(TAG, loginResultDTOMessageDTO.toString());

                        if (loginResultDTOMessageDTO.getCode() == Const.REQUEST_SUCCESS) {
                            LoginResultDTO loginResultDTO = GsonUtils.getInstance().fromJson(String.valueOf(loginResultDTOMessageDTO.getData()), LoginResultDTO.class);
                            if (loginResultDTO.getStatus() == LoginResultDTO.LOGIN_SUCCESS) {
                                Const.TOKEN = loginResultDTOMessageDTO.getToken();
                                Const.USERNAME = loginResultDTOMessageDTO.getUsername();

                                editor.putString("username", Const.USERNAME);
                                editor.putString("token", Const.TOKEN);
                                editor.commit();

                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(LoginActivity.this, loginResultDTOMessageDTO.getMsg(), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(LoginActivity.this, loginResultDTOMessageDTO.getMsg(), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailed(Exception e) {
                        e.printStackTrace();
                    }
                }, MessageDTO.class);
            }
        });

        toRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
